<template>
  <div class="login-container">
    <div v-if="isLogin" class="login-forms">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="密码登录" name="first">
          <el-form
            ref="loginForm"
            :model="pwdLoginForm"
            :rules="loginRules"
            class="demo-ruleForm"
          >
            <h3 class="title">欢迎使用</h3>
            <el-form-item prop="username">
              <el-input
                v-model="pwdLoginForm.username"
                type="text"
                auto-complete="off"
                placeholder="账号"
                prefix-icon="el-icon-user"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="pwdLoginForm.password"
                type="password"
                auto-complete="off"
                placeholder="密码"
                @keyup.enter.native="handlePwdLogin"
                prefix-icon="el-icon-lock"
              >
              </el-input>
            </el-form-item>

            <el-checkbox
              v-model="pwdLoginForm.rememberMe"
              style="margin: 0 0 25px 0; font-size: 10px"
            >
              七天免登陆
            </el-checkbox>
            <el-form-item style="width: 100%">
              <el-button
                :loading="loading"
                size="medium"
                type="primary"
                style="width: 100%"
                @click.native.prevent="handlePwdLogin"
              >
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-form-item>
          </el-form>
          <div class="test-pwd">默认账号：yx23050001 密码：123456</div>
        </el-tab-pane>
        <el-tab-pane label="验证码登录" name="second">
          <el-form
            class="cookForm"
            :model="cookForm"
            :rules="cookRules"
            ref="cookForm"
            label-position="top"
          >
            <h3 class="title">欢迎使用</h3>
            <el-form-item prop="phone">
              <el-input
                placeholder="手机号"
                v-model="cookForm.phone"
                prefix-icon="el-icon-mobile"
              ></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-input placeholder="手机验证码" v-model="cookForm.code">
                <template slot="append">
                  <el-button
                    v-if="cookForm.showloginCode"
                    type="primary"
                    @click="getLoginPhoneCode(cookForm.phone)"
                    >获取验证码</el-button
                  >
                  <div v-else>{{ cookForm.count }}</div>
                </template>
              </el-input>
            </el-form-item>
            <el-checkbox
              v-model="cookForm.automation"
              style="margin: 0 0 25px 0; font-size: 10px"
            >
              未注册手机号自动注册登录
            </el-checkbox>

            <el-form-item>
              <el-button
                type="primary"
                style="width: 100%"
                @click="messageLoginFun"
                >登录</el-button
              >
            </el-form-item>
          </el-form></el-tab-pane
        >
        <div>
          <el-button @click="isLogin = false" type="text" class="register"
            >注册</el-button
          >
        </div>
      </el-tabs>
    </div>
    <div v-else class="login-forms">
      <el-form
        :model="registerForm"
        status-icon
        :rules="registerRules"
        ref="registerForm"
        label-width="0"
        class="demo-ruleForm"
      >
        <h3 class="title">欢迎注册</h3>
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            auto-complete="off"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input placeholder="手机验证码" v-model="registerForm.code">
            <template slot="append">
              <el-button
                type="primary"
                @click="getLoginPhoneCode(registerForm.phone)"
                >获取验证码</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="registerForm.password"
            auto-complete="off"
            placeholder="输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="checkPass">
          <el-input
            type="password"
            v-model="registerForm.checkPass"
            auto-complete="off"
            placeholder="确认密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="registerFun" style="width: 100%"
            >注册</el-button
          >
          <el-button class="back-login" type="text" @click="isLogin = true"
            >已有账号？立即登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div
      class="el-icon-close login-close"
      @click="closeLogin()"
      style="font-size: 19px; font-weight: 600"
    ></div>
  </div>
</template>

<script>
import {
  pwdLoginApi,
  getCodeApi,
  messageLoginApi,
  registerApi,
} from "@/api/login";
import { setToken, setTTLToken } from "@/utils/auth";
export default {
  data() {
    // <!--验证手机号是否合法-->
    let checkTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!this.checkMobile(value)) {
        callback(new Error("手机号码不合法"));
      } else {
        callback();
      }
    };
    //  <!--验证码是否为空-->
    let checkSmscode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机验证码"));
      } else {
        callback();
      }
    };

    // <!--二次验证密码-->
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.registerForm.password !== "") {
        }

        callback();
      }
    };
    return {
      loading: false,
      registerForm: {
        password: "",
        checkPass: "",
        phone: "",
        code: "",
      },
      registerRules: {
        password: [
          { validator: validatePass, trigger: "change" },
          { min: 6, max: 16, message: "密码须为6-16个字符", trigger: "blur" },
        ],
        checkPass: [
          { validator: validatePass2, trigger: "change" },
          { min: 6, max: 16, message: "密码须为个字符", trigger: "blur" },
        ],
        phone: [{ validator: checkTel, trigger: "change" }],
        code: [{ validator: checkSmscode, trigger: "change" }],
      },
      activeName: "first",
      isLogin: true,
      pwdLoginForm: {
        username: "",
        password: "",
        rememberMe: false,
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "账号不能为空" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
      },
      cookForm: {
        phone: "",
        code: "",
        timer: null,
        showloginCode: true, //判断展示‘获取验证码’或‘倒计时’
        count: "", //倒计时时间
        automation: "",
      },
      cookRules: {
        phone: [
          { required: true, trigger: "blur", message: "输入正确的电话号码" },
        ],
        code: [
          { required: true, trigger: "blur", message: "输入接收的验证码" },
        ],
      },
    };
  },
  props: { openLogin: Boolean },
  watch: {},
  methods: {
    closeLogin() {
      this.$emit("changeMsg", false);
    },
    handlePwdLogin() {
      // 校验  表单校验不写？
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 调用api
          pwdLoginApi(this.pwdLoginForm).then((res) => {
            if (res.data.code == 200) {
              if (this.pwdLoginForm.rememberMe) {
                setTTLToken(res.data.data.token, 7);
              } else {
                setToken(res.data.data.token);
              }
              // 调用store 设置参数
              this.$store.commit("setToken", res.data.data.token);
              this.$store.commit("setUserInfo", res.data.data.userInfo);
              // 跳转首页
              location.reload();
              this.closeLogin();
            } else {
              // 提示一下  msg内容
              this.$message({
                type: "error",
                message: res.data.msg,
              });
            }
          });
        } else {
          // 提示一下  msg内容
          this.$message({
            type: "error",
            message: "输入格式不正确！",
          });
        }
      });
    },
    checkTelephone(telephone) {
      var reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!reg.test(telephone)) {
        return false;
      } else {
        return true;
      }
    },
    checkMobile(str) {
      let re = /^1\d{10}$/;
      if (re.test(str)) {
        return true;
      } else {
        return false;
      }
    },
    messageLoginFun() {
      // 校验手机号和验证码
      if (!this.checkTelephone(this.cookForm.phone)) {
        // 校验失败
        this.$message({
          type: "error",
          message: "输入有效的手机号！",
          duration: 1000,
        });
        return;
      }
      if (this.cookForm.code.length != 4) {
        // 校验失败
        this.$message({
          type: "error",
          message: "请输入有效格式验证码",
          duration: 1000,
        });
        return;
      }
      messageLoginApi({
        phone: this.cookForm.phone,
        code: this.cookForm.code,
        register: this.cookForm.automation,
      }).then((res) => {
        if (res.data.code == 200) {
          setToken(res.data.data.token);
          // 调用store 设置参数
          this.$store.commit("setToken", res.data.data.token);
          this.$store.commit("setUserInfo", res.data.data.user);
          // 跳转首页
          this.$router.push({
            path: "/home",
          });
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    getLoginPhoneCode(phone) {
      // 校验手机号码的准确性
      if (!this.checkTelephone(phone)) {
        // 校验失败
        this.$message({
          type: "error",
          message: "输入有效的手机号！",
          duration: 1000,
        });
        return;
      }
      getCodeApi({ userPhone: phone }).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            type: "success",
            message: "发送成功",
          });
        } else {
          this.$message({
            type: "info",
            message: "发送失败",
          });
        }
      });
    },
    registerFun() {
      // 注册
      // 校验表单
      this.$refs.registerForm.validate((valid) => {
        if (!valid) {
        } else {
          registerApi(this.registerForm).then((res) => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "注册成功",
              });
            } else {
              this.$message({
                type: "info",
                message: "注册失败",
              });
            }
          });
        }
      });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
  },
};
</script>

<style>

.login-container {
  background: url(https://p3-pc-weboff.byteimg.com/tos-cn-i-9r5gewecjs/login-resetpwd-bg.png)
    no-repeat rgb(255, 255, 255);
  border-radius: 5px;
  width: 350px;
  position: fixed;
  height: 405px;
  padding: 25px;
  /* box-sizing: content-box; */
  /* background: #fff; */
  z-index: 999;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  transform: scale(0.9);
}

.register {
  float: right;
  font-size: 14px;
  color: rgb(24, 144, 255);
}
.login-container .el-tabs__item {
  text-align: center;
  width: 160px;
}
.title {
  margin: 10px auto 30px auto;
  text-align: center;
  color: #707070;
}
.back-login {
  margin-bottom: 13px;
  float: right;
  font-size: 14px;
  color: rgb(24, 144, 255);
}
.login-forms {
  height: 385px;
  background: #fff;
  border-radius: 8px;
  padding: 10px;
}
.login-close {
  position: absolute;
  color: #747171;
  right: 5px;
  top: 5px;
  cursor: pointer;
}
.test-pwd {
  position: absolute;
  color: #b2b2b2;
  margin-top: -15px;
}
</style>
